package com.example.administrator.szb.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.bean.FBZXBean;
import com.example.administrator.szb.bean.QNBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.Toasts;
import com.example.administrator.szb.util.TokenUtil;
import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.sendtion.xrichtext.RichTextEditor;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by D N on 2017/9/30.
 * 图文发布
 */

public class TWFBActivity extends TakePhotoActivity {

    TakePhoto take = getTakePhoto();
    @Bind(R.id.twfb_fh)
    ImageView twfbFh;
    @Bind(R.id.twfb_text_fb)
    TextView twfbTextFb;
    @Bind(R.id.twfb_edit_bt)
    EditText twfbEditBt;
    @Bind(R.id.et_new_content)
    RichTextEditor et_new_content;
    @Bind(R.id.twfb_image_choose)
    ImageView twfbImageChoose;
    @Bind(R.id.twfb_ll)
    LinearLayout twfbLl;
    int i = 1;//上传图片的张数
    private Subscription subsLoading;
    private Subscription subsInsert;
    String token = TokenUtil.getToken();
    private ProgressDialog insertDialog;
     Gson gson =new Gson();
    ArrayList<String> twfb_info = new ArrayList<>();
    FBZXBean fbzxBean;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.twfb_activity);
        ButterKnife.bind(this);

        insertDialog = new ProgressDialog(this);
        insertDialog.setMessage("正在插入图片...");
        insertDialog.setCanceledOnTouchOutside(false);
        //insertDialog.show();
    }

    /**
     * 开启图片选择
     */
    private void chooseImage() {
        take.onPickMultiple(9);
    }

    @OnClick({R.id.twfb_fh, R.id.twfb_text_fb, R.id.twfb_image_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.twfb_fh:
                finish();
                break;
            case R.id.twfb_text_fb:
                requestFB();
                break;
            case R.id.twfb_image_choose:
                chooseImage();
                break;
        }
    }

    private void requestFB() {
        boolean flag;
        try{
            flag = checkInfo();
        }catch (Exception e){
            e.toString();
            flag = false;
        }


        if (flag) {
            try{
                doRequestFB();
            }catch (Exception e){
                Toasts.show(this, "网络异常，再试一次吧。。。", Toast.LENGTH_SHORT);
            }

        }
    }

    private void doRequestFB() {
        twfbTextFb.setEnabled(false);

        HashMap<String,String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("id", SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("title",twfb_info.get(0));
        map.put("content",twfb_info.get(1));
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_FB_WZ;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, FBZXBean.class, URLAddress.URLBASE + URLAddress.URL_FB_WZ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {

                fbzxBean = (FBZXBean) response;

                if (fbzxBean.getResult() == 1){
                    Toasts.show(TWFBActivity.this, "发布成功", Toast.LENGTH_SHORT);
                    RichTextEditor.URL_IMAGE.clear();
                    finish();
                }else{
                    Toasts.show(TWFBActivity.this, ""+fbzxBean.getErr_msg(), Toast.LENGTH_SHORT);
                }

               // Toasts.show(TWFBActivity.this, "尚未认证成功呢...", Toast.LENGTH_SHORT);
                //finish();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                twfbTextFb.setEnabled(true);
                error.toString();
            }
        });
    }

    private boolean checkInfo() {
        getInfo();
        if(TextUtils.isEmpty(twfb_info.get(0))){
            DialogUtil.showSimpleDialog(this,"请输入标题");
        }else if(TextUtils.isEmpty(twfb_info.get(1))){
            DialogUtil.showSimpleDialog(this,"请输入内容");
        }else{
            return true;
        }
        return false;
    }

    private void getInfo() {
        twfb_info.clear();
        twfb_info.add(twfbEditBt.getText().toString().trim());
        if (TextUtils.isEmpty(getEditData())){

            twfb_info.add("");
        }else{
            twfb_info.add( "<!DOCTYPE html>" +
                    "<html>" +
                    "<head>" +
                    "<meta charset=\"UTF-8\">" +
                    "<title></title>" +
                    "</head>" +
                    "<body>"+getEditData()+
                    "</body>" +
                    "</html>");
        }

    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     */
    private String getEditData() {
        List<RichTextEditor.EditData> editList = et_new_content.buildEditData();
        StringBuffer content = new StringBuffer();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append("<p>"+itemData.inputStr+"</p>");
                //Log.d("RichEditor", "commit inputStr=" + itemData.inputStr);
            } else if (itemData.imagePath != null) {
                content.append("<img src=\"").append(itemData.imagePath).append("\"/>");//itemData.imagePath就是就如图片的url
                //Log.d("RichEditor", "commit imgePath=" + itemData.imagePath);
                //imageList.add(itemData.imagePath);
            }
        }
        return content.toString();
    }

    /**
     * 拍照或者从相片选取相片的回调方法
     *
     * @param result
     */
    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
         insertImagesSync(result);
    }


    /**
     * 上传图片
     */
    private void upImage(String path, String token_local, final TResult s) {
        File data = new File(path);
        /**
         * 压缩图片
         */
        String key = System.currentTimeMillis()+".jpg";
        String token = token_local;
        SampleApplicationLike.getUpLoadManager().put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        insertDialog.setMessage("正在上传第"+i+"/"+s.getImages().size()+"图片");
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if(info.isOK()) {

                            if (i == s.getImages().size()) {
                                insertDialog.dismiss();
                            }
                            i++;
                            Log.i("qiniu", "Upload Success");
                            QNBean b = gson.fromJson(info.response.toString(), QNBean.class);
                            String url_imag = "https://pic.shizhibao.net/"+b.getKey()+"";
                            RichTextEditor.URL_IMAGE.add(url_imag);
                            Toasts.show(TWFBActivity.this, "ok", Toast.LENGTH_LONG);
                        } else {
                            Toasts.show(TWFBActivity.this, "上传图片失败。。。", Toast.LENGTH_SHORT);
                            insertDialog.dismiss();
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                    }
                }, null);
    }

    /**
     * 异步方式插入图片
     * @param data
     */
    private void insertImagesSync(final TResult data){
        i = 1;
        insertDialog.setMessage("正在上传第"+i+"("+data.getImages().size()+")图片");
        insertDialog.show();

        subsInsert = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try{
                    et_new_content.measure(0, 0);
                    ArrayList<TImage> photos = data.getImages();
                    //可以同时插入多张图片
                    for (TImage imagePath : photos) {
                        //Log.i("NewActivity", "###path=" + imagePath);
                        //Bitmap bitmap = ImageUtils.getSmallBitmap(imagePath, width, height);//压缩图片
                        //bitmap = BitmapFactory.decodeFile(imagePath);
                        //imagePath = SDCardUtil.saveToSdCard(bitmap);
                         upImage(imagePath.getOriginalPath(),token,data);
                        //Log.i("NewActivity", "###imagePath="+imagePath);
                        subscriber.onNext(imagePath.getOriginalPath());
                    }
                    subscriber.onCompleted();
                }catch (Exception e){
                    e.printStackTrace();
                    subscriber.onError(e);
                }
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        et_new_content.addEditTextAtIndex(et_new_content.getLastIndex(), "");
                        //Toasts.show(TWFBActivity.this, "插入图片成功", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onError(Throwable e) {
                        //insertDialog.dismiss();
                        Toasts.show(TWFBActivity.this, "插入失败"+e.getMessage(), Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onNext(String imagePath) {
                        et_new_content.insertImage(imagePath, et_new_content.getMeasuredWidth());
                    }
                });
    }

}
